package com.nulldev.util.security.encryptAPI.impls.idea;

import com.nulldev.util.data.Variables;
import com.nulldev.util.data.Base64.Base64;
import com.nulldev.util.security.encryptAPI.Encryptor;

public class IDEA extends Encryptor {
	private final byte[] key;

	public IDEA(final String key) {
		super("encryptapi.tp.rc4", new String[]
			{ "IDEA" }, key);
		this.key = key.getBytes();
	}

	public IDEA(final byte[] key) {
		super("encryptapi.tp.idea", new String[]
			{ "IDEA" }, key);
		this.key = key;
	}

	@Override
	public byte[] encryptToBytes(Object o) {
		Variables.notNullE(o);
		final IdeaCipher ic = new IdeaCipher(new String(this.key), true);
		if (o instanceof byte[]) {
			byte[] d = ((byte[]) o);
			ic.crypt(d);
			return d;
		} else if (o instanceof String) {
			byte[] d = ((String) o).getBytes();
			ic.crypt(d);
			return d;
		} else {
			throw new UnsupportedOperationException("encryptToBytes() -> Unsupported operation on: " + o);
		}
	}

	@Override
	public String encrypt(Object o) {
		Variables.notNullE(o);
		final IdeaCipher ic = new IdeaCipher(new String(this.key), true);
		if (o instanceof byte[]) {
			byte[] d = ((byte[]) o);
			ic.crypt(d);
			return Base64.encodeBase64String(d);
		} else if (o instanceof String) {
			byte[] d = ((String) o).getBytes();
			ic.crypt(d);
			return Base64.encodeBase64String(d);
		} else {
			throw new UnsupportedOperationException("encrypt() -> Unsupported operation on: " + o);
		}
	}

	@Override
	public String decrypt(String o) {
		Variables.notNullE(o);
		final IdeaCipher ic = new IdeaCipher(new String(this.key), false);
		byte[] d = Base64.decodeBase64(o);
		ic.crypt(d);
		return new String(d);
	}

	@Override
	public byte[] decryptToBytes(byte[] o) {
		Variables.notNullE(o);
		final IdeaCipher ic = new IdeaCipher(new String(this.key), false);
		byte[] d = ((byte[]) o);
		ic.crypt(d);
		return d;
	}

	@Override
	public byte[] getKey() {
		return this.key;
	}

	@Override
	public String getKeyAsString() {
		return new String(this.key);
	}
}
